package com.hooview.api.service.impl;

import com.hooview.api.service.VerifyCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springside.modules.utils.number.RandomUtil;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {
//    @Autowired
//    private RedisClient redisClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成手机验证码
     *redis缓存
     * @param mobile
     * @return
     */
    @Override
    public String genCode(String mobile) {
        String code = RandomUtil.nextInt(100000, 999999) + "";
//        redisClient.set(mobile,code,60*60);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set(mobile,code,60*60, TimeUnit.SECONDS);
        return code;
    }

    /**
     * 验证码的校验
     *
     * @param mobile
     * @param code
     * @return
     */
    @Override
    public Boolean isValidCode(String mobile, String code) {
//        VerifyCode vCode = verifyCodeMapper.findByMobileAndCode(mobile, code);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String c = ops.get(mobile);
        if(!StringUtils.isBlank(c) && c.equals(code) ) return true;
        return false;
    }

    @Override
    public void deleteCode(String mobile) {
        stringRedisTemplate.delete(mobile);
    }

}
